﻿/*
Copyright (C) 2008 Stephen Packer

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

function fetch_data() {
    if (!framework.system.network.online) {
        lNoLoginDetails.innerText   = OFFLINE;
        lNoLoginDetails.color       = "#FF0000";
        return;
    }
    if (imgRefresh.src != "refresh.gif") {
        imgRefresh.src = "refresh.gif";
        imgRefresh.rotation = 0;
        imgRefresh.onclick = fetch_data;
    }
    clearInterval(rotateTimer);
    rotateTimer = setInterval("rotateIcon()", 1);
    
    debug.trace("Fetching data from Mint");
	var url         = options.getValue("url");
	var email       = options.getValue("email");
	var password    = options.getValue("password");
	var parameters  = "widget=true&mode=auth&action=Login&email=" + escape(email) + "&password=" + escape(password) + "&" + (new Date).getTime();
	
	if (url.length == 0 || email.length == 0 || password.length == 0) {
		return;
	}

	var req = new XMLHttpRequest();
	if (req.overrideMimeType)  req.overrideMimeType("text/xml");
	req.onreadystatechange = parseMint;
	req.open("POST", url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", parameters.length);
	req.setRequestHeader("Connection", "close");
	req.send(parameters);

	function parseMint() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				if (checkLogin(req.responseText))
                    parseValues(req.responseText);
			} else {
				alerter(ALERT_SERVICE_OFFLINE);
			}
		}
	}
}
function update_caption() {
    var captionText = "Mint";
    if (options.getValue("captionPref") == "Ever")
        captionText += ": " + lVisitsEverTotalValue.innerText + " / " + lVisitsEverUniqueValue.innerText;
    else
    if (options.getValue("captionPref") == "Today")
        captionText += " today: " + lVisitsTodayTotalValue.innerText + " / " + lVisitsTodayUniqueValue.innerText;
    else
    if (options.getValue("captionPref") == "Hour")
        captionText += " this hour: " + lVisitsHourTotalValue.innerText + " / " + lVisitsHourUniqueValue.innerText;
    view.caption = captionText;
}
function checkLogin(text) {
    try {
		var badLogin = /Email\/password combo is incorrect./;
		if (text.match(badLogin)) {
			alerter(ALERT_BAD_LOGIN);
			return false;
		}
		else {
			logged_in = true;
			return true;
		}
	} catch(e) {
        debug.trace("checkLogin() failure: "+e.message)
    }
}

function parseValues(text) {
	var pageData    = text.replace(/\r|\n|\s{2,}/g,"").replace(/&#8216;/g,"'").replace(/&#8217;/g,"'");
	var siteName    = pageData.match( /A Fresh Look at <a href=".+?">(.+?)<\/a>/ );
    // If a non-mint URL is entered, this conditional will find out.
    if (!siteName) {
        alerter(ALERT_BAD_URL);
        return false;
    }
    
    siteName = siteName[1];
    var siteUrl     = pageData.match( /<a id="mint" href="(.+?)">/ )[1];
	var statArray   = pageData.match( /<li id=.+?<\/li>/gim );
	
    lNoLoginDetails.innerText   = siteName;
    lNoLoginDetails.color       = "#FFFFFF";
    options.putValue("siteUrl", siteUrl);
    lNoLoginDetails.onclick = "openMintWebsite()";
    
	for (i=0;i<statArray.length;i++) {
		var listText    = statArray[i];
		var listId      = listText.match( /<li id="([^"]*)">/i )[1];
		if (listId == "visits-ever") {
				lVisitsEverTotalValue.innerText 	= parse_ut(listText, "total");
				lVisitsEverUniqueValue.innerText 	= parse_ut(listText, "unique");
                lVisitsEverTotalValue2.innerText 	= parse_ut(listText, "total");
				lVisitsEverUniqueValue2.innerText 	= parse_ut(listText, "unique");
		}
		if (listId == "visits-today") {
				lVisitsTodayTotalValue.innerText 	= parse_ut(listText, "total");
				lVisitsTodayUniqueValue.innerText 	= parse_ut(listText, "unique");
                lVisitsTodayTotalValue2.innerText 	= parse_ut(listText, "total");
				lVisitsTodayUniqueValue2.innerText 	= parse_ut(listText, "unique");
		}
		if (listId == "visits-hour") {
				lVisitsHourTotalValue.innerText 	= parse_ut(listText, "total");
				lVisitsHourUniqueValue.innerText 	= parse_ut(listText, "unique");
                lVisitsHourTotalValue2.innerText 	= parse_ut(listText, "total");
				lVisitsHourUniqueValue2.innerText 	= parse_ut(listText, "unique");
		}
	}
    setTimeout("clearInterval(rotateTimer);", 500); // makes sure it's noticable that it rotated
    if (imgRefresh.src != "refresh.gif")
        imgRefresh.src = "refresh.gif";
    update_caption();
    
    return true;
}
function parse_ut(text, key) {
	var total_regex 	= /<div class="total">([^<]+)<\/div>/i;
	var unique_regex 	= /<div class="unique">([^<]+)<\/div>/i;
	var span_regex		= /<span>([^<]+)<\/span>/i;
    var output;
	if (key == "total")
			output = text.match( total_regex )[1];
	else
	if (key == "unique")
			output = text.match( unique_regex )[1];
	else
	if (key == "span")
			output = text.match( span_regex )[1];
	else
			output = "";
    return addCommas_skm(output);
}
function addCommas_skm(someNum){
    // compliments: http://lists.evolt.org/pipermail/javascript/2004-June/007409.html
    someNum = someNum+""; // make sure it's a string, not a number
    while (someNum.match(/^\d\d{3}/)){
        someNum = someNum.replace(/(\d)(\d{3}(\.|,|$))/, '$1,$2');
    }
    return someNum;
}
function rotateIcon() {
    imgRefresh.rotation = imgRefresh.rotation + 10;
    if (imgRefresh.rotation >= 720)
        imgRefresh.rotation = 0;
}